package net.lcheng.utils;

import net.coobird.thumbnailator.Thumbnails;
import org.apache.log4j.Logger;

import java.io.*;

/**
 * Created by qiliping on 16/7/20.
 */
public class UploadImgUtils {
    private static Logger log = Logger.getLogger(UploadImgUtils.class);

    /**
     * 处理Base64解码并输出流
     *
     * @param base64
     * @param out
     * @return
     */
    public static boolean base64ToImageOutput(String base64, String savePath, String newFileName,String fileExt) throws IOException {
        if (base64 == null) { // 图像数据为空
            return false;
        }
        String newFilePath = savePath + newFileName + "." + fileExt;
        String thumbFilePath = savePath + newFileName + "_800_800." + fileExt;
        OutputStream out = new FileOutputStream(newFilePath);

        try {

            // Base64解码
            byte[] bytes = org.apache.commons.codec.binary.Base64.decodeBase64(base64);
            for (int i = 0; i < bytes.length; ++i) {
                if (bytes[i] < 0) {// 调整异常数据
                    bytes[i] += 256;
                }
            }
            // 生成jpeg图片
            out.write(bytes);
            out.flush();

//            resizeImage(inputStream,new FileOutputStream(newPath),1000,"jpg");
            log.info("图片保存完毕");

            log.info("开始生成缩略图");
            try {
                InputStream inputStream = new FileInputStream(newFilePath);
                Thumbnails.of(inputStream).size(800,800) .toFile(thumbFilePath);
            }catch (Exception e){
                log.info("生成缩略图失败："+e.getMessage());
            }

            return true;

        } finally {
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}
